import { IsUsed } from './../../../shared/service-proxies/service-proxies';


import { Component, Injector, ViewChild } from '@angular/core';
import { MessageService } from '@abp/message/message.service';
import { Table } from 'primeng/components/table/table';
import { Paginator } from 'primeng/components/paginator/paginator';
import { CommonServiceProxy, MakeTaskServiceProxy, OperationHistoryServiceProxy, OperationLogDto, ProductionAssignmentServiceProxy, ProductionDesignServiceProxy, ProductionTaskOutput, UserSkillDto, UserSkillServiceProxy } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { finalize } from 'rxjs/operators';
import { LazyLoadEvent } from 'primeng/api';


@Component({
    selector: 'app-skill-matrix',
    templateUrl: './skill-matrix.component.html',
    styleUrls: ['./skill-matrix.component.less']
})
export class SkillMatrixComponent extends AppComponentBase {
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('dataTable') dataTable: Table;
    teamList: any = [];
    peopleList: any = [];
    logList: OperationLogDto[];
    actived = false;
    jinengList: any;
    uiItem: any;
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _userSkillServiceProxy: UserSkillServiceProxy,
        private _makeTaskServiceProxy: MakeTaskServiceProxy,
        private _productionAssignmentServiceProxy: ProductionAssignmentServiceProxy,
        private _productionDesignServiceProxy: ProductionDesignServiceProxy,

        private _operationHistoryServiceProxy: OperationHistoryServiceProxy,
        private _commonServiceProxy: CommonServiceProxy,
    ) {
        super(injector);

    }
    tasklist: any = [];//任务编号列表
    queryInfo = {
        id: undefined,//id
        team: undefined,//规格型号
        people: undefined,//发次
        jobNumber: undefined,//任务编号
    };//查询条件
    dialogType: string = '新增'
    addVisible: boolean = false;//弹窗 参数
    llVisible: boolean = false;//履历 参数
    createInfo: any = []
    userList: any[];//调度员下拉
    savingAddDia: boolean = false;//禁止频繁保存操作
    addInfo: UserSkillDto[];
    selectedMembers: ProductionTaskOutput[];
    teamAdd: any
    ngOnInit() {
        this.getUnit()
        this.getSkillList()
    }

    //重置
    reset() {
        this.queryInfo = {
            id: undefined,//id
            team: undefined,//规格型号
            people: undefined,//发次
            jobNumber: undefined,//任务编号
        }
    }
    //弹窗隐藏
    displayclose(): void {
        this.actived = false;
        this.createInfo = [];
        this.teamAdd = undefined;
    }
    deleteTable(index) {
        this.createInfo.splice(index, 1);
    }
    //新增中人员选中禁用
    peopleChange(ev) {
        this.createInfo.forEach(element => {
            element.peopleList.forEach(peopleitem => {
                if (peopleitem.id == ev.id) {
                    peopleitem.disabled = true
                }
            });
        });

    }
    // 新增
    updateStandardDesc(): void {
        this.savingAddDia = true
        // this.createInfo.forEach(element => {
        let item = new UserSkillDto()
        item.id = this.uiItem.id
        item.isUsed = this.uiItem.IsUsed
        item.organizationUnitId = this.uiItem.organizationUnitId
        item.organizationUnit = this.uiItem.organizationUnit
        item.userId = this.uiItem.userId
        item.user = this.uiItem.user
        item.skillId = ""
        item.skill = ""
        let leng = this.uiItem.skillId.length
        this.uiItem.skillId.forEach((skillIdItem, index) => {
            if (index == leng - 1) {
                item.skillId += `${skillIdItem.value}`
                item.skill += `${skillIdItem.label}`

            } else {
                item.skillId += `${skillIdItem.value},`
                item.skill += `${skillIdItem.label},`

            }
        });
        this._userSkillServiceProxy.updateUserSkill(
            item
        )
            .pipe(finalize(() => { this.savingAddDia = false }))
            .subscribe(result => {
                this.addVisible = false
                this._messageService.success('修改成功');
                this.getDescList()
            });

    }
    //新增
    addStandardDesc(): void {
        if (this.createInfo.length == 0) {
            this._messageService.error("请确认添加了数据")
        }
        this.savingAddDia = true
        this.addInfo = []
        this.createInfo.forEach(element => {
            let item = new UserSkillDto()
            item.isUsed = 1
            item.organizationUnitId = this.teamAdd.id
            item.organizationUnit = this.teamAdd.displayName
            item.userId = element.skillDto.userId.id
            item.user = element.skillDto.userId.name
            item.skillId = ""
            item.skill = ""
            let leng = element.skillDto.skillId.length
            element.skillDto.skillId.forEach((skillIdItem, index) => {
                if (index == leng - 1) {
                    item.skillId += `${skillIdItem.value}`
                    item.skill += `${skillIdItem.label}`

                } else {
                    item.skillId += `${skillIdItem.value},`
                    item.skill += `${skillIdItem.label},`

                }
            });
            this.addInfo.push(item)

        });
        this._userSkillServiceProxy.createUserSkill(
            this.addInfo
        )
            .pipe(finalize(() => { this.savingAddDia = false }))
            .subscribe(result => {
                this.addVisible = false
                this._messageService.success('添加成功');
                this.getDescList()
            });

    }
    //添加人员
    addEv() {
        let skillDto = new UserSkillDto()
        let item = {
            skillDto: skillDto,
            teamList: this.teamList,
            peopleList: this.peopleList,
            jinengList: this.jinengList
        }
        this.createInfo.push(
            item
        )
    }
    teamChangeEv(ev) {
        let idArr = []
        idArr.push(ev.id)
        this.getUsersById(idArr)
    }
    //班组下拉
    getUnit() {
        // /ProductionAssignment/GetOrganizationUnit
        this._productionAssignmentServiceProxy.getOrganizationUnit(
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.teamList = result
                let arr = []
                arr.push(this.teamList[0].id)
                this.getUsersById(arr)

            });
    }
    //新增人员
    addSkillMatrix() {
        this.getUnit()
        this.getSkillList()
        this.dialogType = '新增';
        this.addVisible = true;
        this.actived = true
        this.addEv()
    }
    /**
      根据班组Id获取该班组下的人员
      */
    getUsersById(idArr): any {
        // /ProductionAssignment/GetOrganizationUnitUsersById
        this._productionAssignmentServiceProxy.getOrganizationUnitUsersById(idArr)
            .pipe(finalize(() => { }))
            .subscribe(result => {

                this.peopleList = result
                this.peopleList.forEach(element => {
                    element.disabled = false
                });
                this.createInfo.forEach(element => {
                    element.peopleList = this.peopleList
                });
            });
    }
    //技能类型
    getSkillList(): any {
        this._userSkillServiceProxy.getSkillList()
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.jinengList = result
                this.createInfo.forEach(element => {
                    element.jinengList = result
                });
            });
    }

    /**
     * 人员矩阵主列表查询 
     */
    getDescList(event?: LazyLoadEvent): void {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        this._userSkillServiceProxy.getUserSkillList(
            this.queryInfo.team ? this.queryInfo.team.id : undefined,
            this.queryInfo.people ? this.queryInfo.people.id : undefined,
            this.primengTableHelper.getSorting(this.dataTable),//undefined
            this.primengTableHelper.getMaxResultCount(this.paginator, event),//10
            this.primengTableHelper.getSkipCount(this.paginator, event)//0
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();

            });
    }
    //履历
    llVisibleEv(id) {

        this._operationHistoryServiceProxy.getOperationLogList(
            id
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.logList = result
                this.llVisible = true
            });

    }
    //启用 停用
    seeDetail(item) {
        if (item.isUsed == 1) {
            item.isUsed = 0
        } else {
            item.isUsed = 1
        }
        this._userSkillServiceProxy.updateUserSkill(
            item
        )
            .pipe(finalize(() => { this.savingAddDia = false }))
            .subscribe(result => {
                this.addVisible = false
                this._messageService.success(item.isUsed == 1 ? '启用成功' : '停用成功');
                this.getDescList()
            });

    }
    //修改
    editDetail(item) {
        this.actived = true;
        // this.createInfo.push(JSON.parse(JSON.stringify(item)))
        this.uiItem = JSON.parse(JSON.stringify(item))
        this.dialogType = '修改';
        this.addVisible = true;
        let skillIdArr = []
        let skillid = this.uiItem.skillId.split(",")
        for (let index = 0; index < skillid.length; index++) {
            const element = skillid[index];
            let skillId = this.jinengList.filter((ele, index) => {
                return ele.value == element
            })
            skillIdArr.push(skillId[0])
        }

        this.uiItem.skillId = skillIdArr
    }

}
